package com.sirdc.modules.sys.web.HardWork;

import com.sirdc.modules.core.filter.Paging;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.filter.NodeNewschedulesModel;
import com.sirdc.modules.sys.service.PlanTimeReckonService;
import com.sirdc.modules.sys.util.RedisUtils;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Project.entity.NewProjects;
import net.huashitong.Project.filter.NewProjectsFilter;
import net.huashitong.Project.service.ExportService;
import net.huashitong.Project.service.NewProjectsService;
import net.huashitong.node.entity.NodeNewschedules;
import net.huashitong.node.service.NodeNewschedulesService;
import net.huashitong.node.utile.DateUtil;
import net.huashitong.oversee.entity.SupervisionTask;
import net.huashitong.oversee.filter.CoordinateFilter;
import net.huashitong.oversee.filter.SupervisionTaskFilter;
import net.huashitong.oversee.service.CoordinateService;
import net.huashitong.oversee.service.SupervisionTaskService;
import net.huashitong.user.entity.BnpUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.*;

import static net.huashitong.utils.UtilsTools.getClientIp;


/**
 * 项目管理
 * Created by hyp1202 on 2018/7/10.
 */
@Controller
@RequestMapping("/projectManger")
public class SysProjectMangerController {

    @Autowired
    private NewProjectsService newProjectsService;
    @Autowired
    private NodeNewschedulesService nodeNewschedulesService;
    @Autowired
    private PlanTimeReckonService planTimeReckonService;
    @Autowired
    private SupervisionTaskService supervisionTaskService;
    @Autowired
    private ExportService exportService;

    @RequestMapping(value = "/go/list", method = RequestMethod.GET)
    public String goListProject(@ModelAttribute NewProjectsFilter filter, Model model, HttpServletRequest request) {
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        if (ObjectUtils.isBlank(bnpUser)) {
            return "/modules/login/login";
        }
        //待办任务个数
        int nodeCount = (int) WebUtils.getSessionAttribute(request, "nodeCount");
        model.addAttribute("nodeCount", nodeCount);

        int myTaskNum = (int) WebUtils.getSessionAttribute(request, "myTaskNum");
        int quetionNum = (int) WebUtils.getSessionAttribute(request, "quetionNum");
        model.addAttribute("myTaskNum", myTaskNum);
        model.addAttribute("quetionNum", quetionNum);

        int myTackTaskNum = (int) WebUtils.getSessionAttribute(request, "myTackTaskNum");
        model.addAttribute("myTackTaskNum", myTackTaskNum);

        model.addAttribute("leftType", "项目管理");
        Paging p = new Paging();
        if (filter.getPage() == null) {
            filter.setPage(0);
        }
        p.setCurrentPage(filter.getPage() + 1);
        filter.setPaging(p);
        List<NewProjects> list = newProjectsService.getProjectInfo(filter);
        double page = newProjectsService.getProjectSumPage(filter);
        model.addAttribute("totalPage", page);
        model.addAttribute("list", list);
        model.addAttribute("branchType", bnpUser.getBranchType());

        return "/modules/hardWork/user_xmProject";
    }

    /**
     * 条件搜索
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Map<String, Object> searchProjects(@RequestBody NewProjectsFilter filter, Model model) {
        Map<String, Object> map = new HashMap<>();
        Paging p = new Paging();
        double page = 0;
        if (filter.getPage() == null) {
            filter.setPage(0);
        }
        filter.setCurrentPage(filter.getPage() + 1);
        if ("5".equals(filter.getStatus())) {
            List<NewProjects> list = new ArrayList<>();
            double currentSumPage;
            for (Integer i = 0; i < 3; i++) {
                filter.setStatus(i.toString());
                list.addAll(newProjectsService.getProjectInfo(filter));
                currentSumPage = newProjectsService.getProjectSumPage(filter);
                if (currentSumPage > page) {
                    page = currentSumPage;
                }
            }
            map.put("totalPage", page);
            map.put("list", list);
            model.addAttribute("totalPage", page);
            return map;
        }
        List<NewProjects> list = newProjectsService.getProjectInfo(filter);
        page = newProjectsService.getProjectSumPage(filter);
        map.put("totalPage", page);
        map.put("list", list);
        model.addAttribute("totalPage", page);
        return map;
    }

    /**
     * 查询···审核通过未通过
     *
     * @param filter
     * @param model
     * @return
     */
    /*
    @ResponseBody
    @RequestMapping(value = "/query")
    public Object query(@ModelAttribute NewProjectsFilter filter, Model model) {
        Map<String, Object> map = new HashMap<>();
        Paging p = new Paging();
        double page = 0;
        if (filter.getPage() == null) {
            filter.setPage(0);
        }
        filter.setCurrentPage(filter.getPage() + 1);
        if ("5".equals(filter.getStatus())) {
            List<NewProjects> list = new ArrayList<>();
            double currentSumPage;
            for (Integer i = 0; i < 3; i++) {
                filter.setStatus(i.toString());
                list.addAll(newProjectsService.getProjectInfo(filter));
                currentSumPage = newProjectsService.getProjectSumPage(filter);
                if (currentSumPage > page) {
                    page = currentSumPage;
                }
            }
            map.put("totalPage", page);
            map.put("list", list);
            model.addAttribute("totalPage", page);
            return map;
        }
        List<NewProjects> list = newProjectsService.getProjectInfo(filter);
        page = newProjectsService.getProjectSumPage(filter);
        map.put("totalPage", page);
        map.put("list", list);
        model.addAttribute("totalPage", page);
        return map;
    }
    */


    /**
     * 审核通过
     *
     * @param filter
     * @param request
     */
    @RequestMapping(value = "/pass")
    public String passProject(@ModelAttribute NewProjectsFilter filter, HttpServletRequest request) throws ParseException {
        String ip = getClientIp(request);
        BnpUser user = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        newProjectsService.initPassProject(filter);
        NewProjects project = newProjectsService.getById(filter.getSysId());
        project.setStatus("3");     //3表示项目被管理员审核通过
        project.setPlanBeginDate(DateUtil.getDate());
        //排出项目完成时间（对单个项目进行审批）
        List<String> allProjects = new ArrayList<>();
        allProjects.add(filter.getSysId());
        List<NodeNewschedulesModel> models = exportService.iii(allProjects);
        List<NodeNewschedulesModel> list = new ArrayList<>();
        for (NodeNewschedulesModel model : models) {
            if("1".equals(model.getState())){
                list.add(model);
            }
        }
        String planEndTimeFlag = list.get(list.size() - 1).getPlanEndTime();
        String factFinishDate = list.get(list.size() - 1).getFactFinishDate();
        //startTime:项目的开工时间
        project.setStartTime(StringUtils.isBlank(planEndTimeFlag) ? factFinishDate : planEndTimeFlag);
        newProjectsService.update(project, ip, user);
        return "redirect:/projectManageSuper";
    }

    /**
     * 审核不通过
     *
     * @param filter
     * @param model
     */
    @RequestMapping(value = "/noPass")
    public String noPassProject(@ModelAttribute NewProjectsFilter filter, Model model) {
        newProjectsService.initNoPassProject(filter);
        return "redirect:/projectManageSuper";
    }

    /**
     * 暂停项目
     *
     * @param filter
     * @param model
     * @return
     */
    @RequestMapping(value = "/pause", method = RequestMethod.POST)
    public String pauseProject(@RequestBody NewProjectsFilter filter, Model model) {
        //更改项目状态为暂停
        newProjectsService.initPauseProject(filter);
        //查询当前项目已开始的节点
        List<NodeNewschedules> nodeList = nodeNewschedulesService.getNodeByProjectIdAndStatus(filter.getSysId(), "1");
        //将已开始状态改为暂停
        for (NodeNewschedules nodeNewschedules : nodeList) {
            nodeNewschedules.setStatus("3");
            nodeNewschedulesService.update(nodeNewschedules);
        }
        return "redirect:/projectManageSuper";
    }

    /**
     * 开始项目
     *
     * @param filter
     * @param model
     * @return
     */
    @RequestMapping(value = "/start", method = RequestMethod.POST)
    public String startProject(@RequestBody NewProjectsFilter filter, Model model) {
        //更改项目状态为开始
        newProjectsService.initStartProject(filter);
        //查询当前项目已开始的节点
        List<NodeNewschedules> nodeList = nodeNewschedulesService.getNodeByProjectIdAndStatus(filter.getSysId(), "3");
        //将已暂停状态改为开始
        for (NodeNewschedules nodeNewschedules : nodeList) {
            nodeNewschedules.setStatus("1");
            nodeNewschedulesService.update(nodeNewschedules);
        }
        return "redirect:/projectManageSuper";
    }


    /**
     * 查看项目节点信息
     *
     * @param filter
     * @param model
     * @return
     */
    @RequestMapping(value = "/queryNode")
    public String queryNodeByProjectId(@ModelAttribute NewProjectsFilter filter, Model model, HttpServletRequest request, @RequestParam String sysId) throws ParseException {

        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        if (ObjectUtils.isBlank(bnpUser)) {
            return "/modules/login/login";
        }
        SupervisionTaskFilter taskFilter = new SupervisionTaskFilter();
        taskFilter.setProjectId(sysId);
        List<SupervisionTask> tasks = supervisionTaskService.getTaskListsNoPage(taskFilter);
        Map<String, SupervisionTask> nodeTaskMap = new HashMap<>();
        for (SupervisionTask t : tasks) {
            if (!nodeTaskMap.containsKey(t.getNodeId())) {
                nodeTaskMap.put(t.getNodeId(), t);
            }
        }
        int supervisionCount = 0;
        if (ObjectUtils.isNotBlank(tasks) && tasks.size() > 0) {
            for (int i = 0; i < tasks.size(); i++) {
                supervisionCount = supervisionCount +
                        Integer.parseInt(StringUtils.isBlank(tasks.get(i).getTasktimes()) ?
                                "1" : tasks.get(i).getTasktimes());
            }
        }


        if ("0".equals(bnpUser.getBranchType()) && "经办人".equals(bnpUser.getRole())) {
            //经办人，业主单位
            model.addAttribute("leftType", "我的项目");
        } else /*if ("1".equals(bnpUser.getBranchType()) && "经办人".equals(bnpUser.getRole())){
            //经办人，审批部门
        }*/ {
            model.addAttribute("leftType", "项目管理");
        }

        List<NodeNewschedulesModel> models = new ArrayList<>();
        filter.setSysId(sysId);
        NewProjects projectList = newProjectsService.getProjectInfo(filter).get(0);
        // state:2 == 不需要(Dao层条件是'!=')
        List<NodeNewschedules> nodeList = nodeNewschedulesService.getNodeByProjectIdAndState(filter.getSysId(), "");
        //各个节点的前置节点
        Map<String, Object> preOfNodeMap = new TreeMap<>();
        for (NodeNewschedules n : nodeList) {
            //筛选确定的节点
            if ("1".equals(n.getState())) {
                //大节点
                if ("1".equals(n.getType())) {
                    if (!preOfNodeMap.containsKey(n.getNodeId())) {
                        preOfNodeMap.put(n.getNodeId(), n.getPreNodeId());
                    }
                } else {
                    //小节点
                    if (!preOfNodeMap.containsKey(n.getNodeId())) {
                        preOfNodeMap.put(n.getNodeId(), preOfNodeMap.get(n.getNodeIds()));
                    }
                }
            }
            if (StringUtils.isNotBlank(n.getFactTime()) && StringUtils.isNotBlank(n.getPlanTime())) {
                if (!"2".equals(n.getStatus())) {
                    n.setIsDelay("-1");     //未完成
                    continue;
                }
                int factTime = Integer.parseInt(n.getFactTime());
                int planTime = Integer.parseInt(n.getPlanTime());
                if (factTime > planTime) {        //实际时间大于计划时间----逾期
                    n.setIsDelay("1");
                } else if (factTime < planTime) {  //实际时间大于计划时间----超前
                    n.setIsDelay("2");
                } else if (factTime == planTime) { //实际时间大于计划时间----正常
                    n.setIsDelay("0");
                }
            }
            n.setCreateDate(projectList.getCreateDate());

        }
        for (NodeNewschedules n : nodeList) {
            NodeNewschedulesModel m = new NodeNewschedulesModel();
            //对象复制n->m
            BeanUtils.copyProperties(n, m);
            models.add(m);
        }
        //推算计划时间
        models = planTimeReckonService.reckonPlanTime(models, preOfNodeMap);
        //批量更新时间状态
//        nodeNewschedulesService.batchUpdateObject(nodeList);
        model.addAttribute("projectList", projectList);

        List<NodeNewschedulesModel> bigNodeModel = new ArrayList<>();       //大节点
        List<NodeNewschedulesModel> smallNodeModel = new ArrayList<>();     //小节点
        List<NodeNewschedulesModel> noUseNodeModel = new ArrayList<>();     //无用节点
        List<NodeNewschedulesModel> resultNodeModel = new ArrayList<>();     //无用节点

        int factUseTime = 0;    //实际用时
        int planUseTime = 0;    //计划用时
        int factUseTimeAll = 0;    //所有实际用时
        int planUseTimeAll = 0;    //所有计划用时

        StringBuffer strBufFinish = new StringBuffer();
        StringBuffer strBufNoFinish = new StringBuffer();
        StringBuffer strBufBegin = new StringBuffer();

        String planTimeInBegin = "0";    //进行中节点计划用时

        int noFinishNodeNum = 0;         //未完成节点个数
        int doingNodeNum = 0;            //进行中节点个数
        int finishedNodeNum = 0;         //已完成节点个数
        for (NodeNewschedulesModel m : models) {
            if ("1".equals(m.getState()) && "1".equals(m.getType())) {
                //确定的大节点
                if (StringUtils.isBlank(m.getPlanBeginDate()) && StringUtils.isBlank(m.getPlanBeginTime())) {
//                    noUseNodeModel.add(m);
//                    continue;
                }
                bigNodeModel.add(m);
                if ("2".equals(m.getStatus())) {
                    strBufFinish.append(m.getNodeId() + ";");
                    factUseTime = factUseTime + Integer.parseInt(StringUtils.isBlank(m.getFactTime()) ? "0" : m.getFactTime());
                    finishedNodeNum++;
                } else {
                    noFinishNodeNum++;
                    strBufNoFinish.append(m.getNodeId() + ";");
                    planUseTime = planUseTime + Integer.parseInt(StringUtils.isBlank(m.getPlanTime()) ? "0" : m.getPlanTime());
                }
                factUseTimeAll = factUseTimeAll + Integer.parseInt(StringUtils.isBlank(m.getFactTime()) ? "0" : m.getFactTime());
                planUseTimeAll = planUseTimeAll + Integer.parseInt(StringUtils.isBlank(m.getPlanTime()) ? "0" : m.getPlanTime());
            } else if ("1".equals(m.getState()) && "2".equals(m.getType())) {
                //确定的小节点
                if (StringUtils.isBlank(m.getPlanBeginDate()) && StringUtils.isBlank(m.getPlanBeginTime())) {
//                    noUseNodeModel.add(m);
//                    continue;
                }
                if ("1".equals(m.getStatus())) {
                    strBufBegin.append(m.getNodeId() + ";");
                    planTimeInBegin = m.getPlanTime();
                    doingNodeNum++;
                }
                smallNodeModel.add(m);
            } else {
                noUseNodeModel.add(m);
            }
        }
        //排序实际开始时间正序排，如果没有实际开始时间则取计划开始时间
        Collections.sort(bigNodeModel, new Comparator<NodeNewschedulesModel>() {
            @Override
            public int compare(NodeNewschedulesModel m1, NodeNewschedulesModel m2) {
                String factBegin1 = m1.getNodePlanStartDate();//实际开始时间
                if (StringUtils.isBlank(factBegin1)) {
                    if (StringUtils.isBlank(m1.getPlanBeginTime())) {
                        return 1;
                    }
                    factBegin1 = m1.getPlanBeginTime();//计划开始时间
                }
                long longFactBegin1 = Long.valueOf(factBegin1.replace(".", ""));

                String factBegin2 = m2.getNodePlanStartDate();//实际开始时间
                if (StringUtils.isBlank(factBegin2)) {
                    if (StringUtils.isBlank(m2.getPlanBeginTime())) {
                        return 1;
                    }
                    factBegin2 = m2.getPlanBeginTime();//计划开始时间
                }
                long longFactBegin2 = Long.valueOf(factBegin2.replace(".", ""));

                if (longFactBegin1 < longFactBegin2) {
                    return -1;
                } else if (longFactBegin1 == longFactBegin2) {
                    return 0;
                } else {
                    return 1;
                }
            }
        });
        for (NodeNewschedulesModel big : bigNodeModel) {
            resultNodeModel.add(big);
            for (NodeNewschedulesModel small : smallNodeModel) {
                if (big.getNodeId().equals(small.getNodeIds())) {
                    resultNodeModel.add(small);
                }
            }
        }
        resultNodeModel.addAll(noUseNodeModel);
//        model.addAttribute("nodeList", resultNodeModel);
        //督查节点（小节点）
        List<NodeNewschedulesModel> smallSupervisionNodes = new ArrayList<>();
        for (NodeNewschedulesModel m : resultNodeModel) {
            if (nodeTaskMap.containsKey(m.getNodeId())) {
                m.setTaskId(nodeTaskMap.get(m.getNodeId()).getSysId());
                m.setTaskTimes(nodeTaskMap.get(m.getNodeId()).getTasktimes());
                smallSupervisionNodes.add(m);
            }
        }


        //节点最终结果
        List<NodeNewschedulesModel> resultNodes = new ArrayList<>();
        Map<String, NodeNewschedulesModel> resultBigMaps = new HashMap<>();

        if (StringUtils.isNotBlank(filter.getSupervisionFlag())) {
            if ("true".equals(filter.getSupervisionFlag())) {
                //查看督查节点
                for (NodeNewschedulesModel node : resultNodeModel) {
                    if ("1".equals(node.getType())) {
                        //大节点
                        if (!resultBigMaps.containsKey(node.getNodeId())) {
                            resultBigMaps.put(node.getNodeId(), node);
                        }
                    }
                }
                for (NodeNewschedulesModel m : smallSupervisionNodes) {
                    String bigNode = m.getNodeIds();
                    if (resultBigMaps.containsKey(bigNode)) {
                        NodeNewschedulesModel big = resultBigMaps.get(bigNode);
                        if (!resultNodes.contains(big)) {
                            resultNodes.add(big);
                            resultNodes.add(m);
                        } else {
                            resultNodes.add(m);
                        }
                    }
                }
            } else {
                resultNodes.addAll(resultNodeModel);
            }
        } else {
            resultNodes.addAll(resultNodeModel);
        }

        StringBuffer stringBuffer = new StringBuffer();
        if (smallSupervisionNodes.size() > 0) {
            for (int i = 0; i < smallSupervisionNodes.size(); i++) {
                if (i == 0) {
                    stringBuffer.append(smallSupervisionNodes.get(i).getNodeId());
                } else {
                    stringBuffer.append("、" + smallSupervisionNodes.get(i).getNodeId());
                }
            }
            model.addAttribute("taskNodes", stringBuffer.toString());
        } else {
            model.addAttribute("taskNodes", "");
        }

        //最终节点，加下个节点展示
        resultNodes = nodeNewschedulesService.addNextNodeDealWith(resultNodes);
        model.addAttribute("nodeList", resultNodes);
        int myTaskNum = (int) WebUtils.getSessionAttribute(request, "myTaskNum");
        int quetionNum = (int) WebUtils.getSessionAttribute(request, "quetionNum");
        model.addAttribute("myTaskNum", myTaskNum);
        model.addAttribute("quetionNum", quetionNum);

        int myTackTaskNum = (int) WebUtils.getSessionAttribute(request, "myTackTaskNum");
        model.addAttribute("myTackTaskNum", myTackTaskNum);

        model.addAttribute("branchType", bnpUser.getBranchType());

        model.addAttribute("factUseTime", factUseTime);
        model.addAttribute("strBufFinish", strBufFinish.toString());
        model.addAttribute("planUseTime", planUseTime);
        model.addAttribute("strBufNoFinish", strBufNoFinish.toString());


        model.addAttribute("noFinishNodeNum", noFinishNodeNum + "");  //未完成节点个数
        model.addAttribute("doingNodeNum", doingNodeNum + "");        //进行中节点个数
        model.addAttribute("finishedNodeNum", finishedNodeNum + "");  //已完成节点个数

        //所有节点
        model.addAttribute("factUseTimeAll", factUseTimeAll);
        model.addAttribute("planUseTimeAll", planUseTimeAll);

        //进行中的节点
        model.addAttribute("planTimeInBegin", planTimeInBegin);
        model.addAttribute("strBufBegin", strBufBegin.toString());
        //sysId
        model.addAttribute("sysId", sysId);

        //总共督查的次数
        model.addAttribute("supervisionCount", supervisionCount + "");
        return "/modules/hardWork/projectInfo";
    }
}
